using System;
using System.IO;
using System.Web;
using ECatalog.Models.Helpers;

namespace ECatalog.Models.Organizations
{
    public class OrganizationBuilder : IOrganizationBuilder
    {
        private readonly IOrganizationRepository organizationRepository;

        public OrganizationBuilder(IOrganizationRepository organizationRepository)
        {
            this.organizationRepository = organizationRepository;
        }

        private static string StorageRoot
        {
            get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); } //Path should! always end with '/'
        }

        public void SaveFile(HttpPostedFileBase uploadedFile, Organization organization)
        {
            if (uploadedFile.ContentType.Equals("image/jpeg") || uploadedFile.ContentType.Equals("image/png") || uploadedFile.ContentType.Equals("image/gif"))
            {
                var file = uploadedFile;
                var fileName = String.Format("{0}-{1}", Guid.NewGuid(), file.FileName.ToLower());
                var trimName = fileName.Remove(fileName.LastIndexOf('.'));

                var path = Path.Combine(StorageRoot, "Organization-" + organization.OrganizationId.ToString(),"Logo-"+ trimName);
                var path320 = Path.Combine(path, "320x240\\");
                var path800 = Path.Combine(path, "800x600\\");
                ImageHelper.CreateDirectory(path);
                ImageHelper.CreateDirectory(path320);
                ImageHelper.CreateDirectory(path800);

                if (Directory.Exists(path) && Directory.Exists(path320) && Directory.Exists(path800))
                {
                    ImageHelper.BuildImage(file, path320, fileName, 320, 240);
                    ImageHelper.BuildImage(file, path800, fileName, 800, 600);
                }
                organization.LogoUrl = trimName;
                organization.TypeImage = ImageHelper.GetImageType(uploadedFile.ContentType);
                organizationRepository.Edit(organization);
            }
        }
    }
}